package com.xiaoha.pogy.controllers;

import com.xiaoha.pogy.dao.BookRepository;
import com.xiaoha.pogy.entities.Book;
import com.xiaoha.pogy.services.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("books")
public class BookController {

    @Autowired
    BookService bookService;


    @GetMapping

    public String displayBookshelves(Model model) {
        List<Book> books = bookService.getAll();
        model.addAttribute("books", books);
        return "books/list-books";
    }


    @GetMapping("/new")
    public String displayBookFrom(Model model) {
        Book aBook = new Book();
        model.addAttribute("book", aBook);

        return "books/new-book";
    }


    @PostMapping("/save")
    public String createBook(Model model, @Valid Book book, Errors errors) {

        if (errors.hasErrors()) return "books/new-book";
        // 使用book crudRepository保存数据库
        bookService.save(book);
        return "redirect:/books";
    }

    @GetMapping("/update")
    public String displayBookUpdateFrom(@RequestParam("id") long theId, Model model) {

        Book theBook = bookService.findByStudentId(theId);
        model.addAttribute("book",theBook);
        return "books/new-book";
    }

    @GetMapping("/delete")
    public String deleteBook(@RequestParam("id") long theId, Model model){

        Book theBook = bookService.findByBookId(theId);
        bookService.delete(theBook);
        return "redirect:/books";

    }

}

